package water.tieba.utils;

import java.util.LinkedHashMap;
import java.util.Map;

import tieba.core.entity.Tie;
import tieba.core.entity.TieBar;
import tieba.core.exception.DefineException;
import tieba.core.exception.VerifycodeException;
import tieba.core.utils.CommonsUtils;
import tieba.core.utils.TBUtils;
import cl.tools.http.method.BasicMethod;

import com.jayway.restassured.response.Cookie.Builder;

public class WaterUtils {

	public static void reply(String cookie, String content, String tid) {
		tid = CommonsUtils.regex(".?(\\d+)", tid, 1);
		System.out.println(tid);
		String url = "http://c.tieba.baidu.com/c/c/post/add";
		TieBar bar = TBUtils.getBarByTid(tid);
		Map<String, Object> ps = new LinkedHashMap<>();
		ps.put("BDUSS", cookie);
		ps.put("_client_type", "4");
		ps.put("content", content);
		ps.put("fid", bar.getFid());
		ps.put("kw", bar.getFn());
		ps.put("tbs", TBUtils.getTbs(new Builder("BDUSS", cookie).build()));
		ps.put("tid", tid);
		ps.put("sign", TBUtils.getSign(ps));
		String body = BasicMethod.post(url, ps).asString();
		System.out.println(body);
	}

	public static TieBar getFidByBarName(String barName) {
		TieBar bar = new TieBar();
		String url = "http://tieba.baidu.com/mo/q-wapp/m?kw=" + barName;
		String body = BasicMethod.get(url).asString();
		String fid = CommonsUtils.regex("name=\"fid\" value=\"(\\d+)\"", body,
				1);
		if (fid == null || "".equals(fid.trim()))
			throw new DefineException("吧名错误!", barName);
		bar.setFid(fid);
		bar.setFn(barName);
		return bar;

	}

	public static void sendTie(String cookie, TieBar bar, Tie tie) {
		if (bar.getFid() == null || "".equals(bar.getFid().trim()))
			bar = getFidByBarName(bar.getFn());
		String url = "http://c.tieba.baidu.com/c/c/thread/add";
		Map<String, Object> ps = new LinkedHashMap<>();
		ps.put("BDUSS", cookie);
		ps.put("_client_type", "2");
		ps.put("content", tie.getContent());
		ps.put("fid", bar.getFid());
		ps.put("kw", bar.getFn());
		ps.put("new_vcode", "1");
		ps.put("tbs", TBUtils.getTbs(new Builder("BDUSS", cookie).build()));
		ps.put("title", tie.getTitle());
		ps.put("sign", TBUtils.getSign(ps));
		String body = BasicMethod.post(url, ps).asString();
		Integer error_code = CommonsUtils.getErrorCode(body);
		if(error_code!=null && error_code == 5)
			throw new VerifycodeException("验证码拦截");
	}
}
